import axios from 'axios'
import { CacheUserUtil } from '@/assets/js/utils/CacheUserUtil'
import router from '@/router/index'

import type { HttpResponse } from '@/assets/js/utils/entity/HttpResponse'

const baseURL = 'http://127.0.0.1:9999'

const instance = axios.create({
    // baseURL 需要设置为反向代理前缀，不能设置绝对路径URL
    baseURL: baseURL,
    timeout: 5000,
    withCredentials: false,
    headers: { 'X-Custom-Header': 'zuiyu' }
})

// 实例添加请求拦截器
instance.interceptors.request.use(config => {
    const token = CacheUserUtil.getToken()
    if (token && !config.headers.Authorization) {
        config.headers.Authorization = 'bearer ' + token
    }
    return config
}, error => {
    return error
})

// 最后一次更新token时间
let lastTokenUpdateTime: number = new Date().getTime()

// 响应拦截器
instance.interceptors.response.use(response => {
    judgeToken()
    if (response.status === 200) {
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response)
    }
}, error => {
    if (error.response.status) {
        switch (error.response.status) {
            // 401: 未登录
            // 未登录则跳转登录页面，并携带当前页面的路径
            // 在登录成功后返回当前页面，这一步需要在登录页操作
            case 401:
            // 403: 登录过期
            case 403:
                CacheUserUtil.clear()
                router.push('/')
                break
        }
        // judgeToken()
        return Promise.reject(error.response)
    }
})

const refreshToken = () => {
    const url = `/ams-auth/oauth/token?grant_type=refresh_token&refresh_token=${CacheUserUtil.getRefreshToken()}`
    return instance.post(url, null, {
        headers: {
            Authorization: 'Basic YW1zOmFtcw=='
        }
    })
}

const judgeToken = async () => {
    const now = new Date().getTime()
    const x = now - lastTokenUpdateTime
    if (x > 5 * 1000 * 60) {
        console.log('重新获取token开始')
        const res = await refreshToken() as unknown as HttpResponse
        console.log('重新获取token结束')
        if (res.ok) {
            lastTokenUpdateTime = new Date().getTime()
            const token = res.data.access_token
            const rToken = res.data.refresh_token
            CacheUserUtil.setToken(token)
            CacheUserUtil.setRefreshToken(rToken)
        }
    }
}

export { instance }